﻿using Abp.Runtime.Caching;
using Microsoft.AspNetCore.Mvc;
using NetCore.Extensions;
using NetCore.Helper;
using System.ComponentModel;
using System.DrawingCore;
using System.DrawingCore.Imaging;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using NetCore.Dtos;

namespace NetCore.PersonalCaches
{
    /// <summary>
    /// 个性化缓存 统一几种管理
    /// </summary>
    [Description("个性化缓存")]
    public class PersonalCacheAppService : NetCoreAppServiceBase, IPersonalCacheAppService
    {
        private ICacheManager _cacheManager;
        private readonly IHttpContextAccessor _httpContext;
        public PersonalCacheAppService(
            IHttpContextAccessor httpContext,
            ICacheManager cacheManager)
        {
            _httpContext = httpContext;
            _cacheManager = cacheManager;
        }

        #region 使用windows ImageHelper画验证码 返回文件与bitmap

        /// <summary>
        /// 获取图片验证码(缓存验证码5分钟有效)
        /// </summary>
        /// <returns></returns>
        public async Task<Bitmap> Verify()
        {
            var image = ImageHelper.CreateVerifyCode(out string code);
            await _cacheManager.GetCache(NetCoreConsts.PersonalCaches).SetAsync("CheckCode", code);
            //var strbase64 = await ImageHelper.GetBase64FromImageAsync(image);
            return image;
        }
        /// <summary>
        /// 获取图片验证码gif文件(缓存验证码5分钟有效)
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> VerifyCode()
        {
            var bitmap = VerifyCodeHelper.CreateVerifyCode(out string code);
            await _cacheManager.GetCache(NetCoreConsts.PersonalCaches).SetAsync("CheckCode", code);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);//png/gif
            return FileExtension.FileContentResult(stream.ToArray(), "image/gif");
        }

        #endregion

        #region SixLabors.ImageSharp 画验证码 返回文件与base64

        /// <summary>
        /// Get获取验证码图片
        /// </summary>
        /// <returns></returns>
        public FileResult GetValidCodeImage()
        {
            var input = new ValidCodeImageInputDto();
            _cacheManager.GetCache(NetCoreConsts.PersonalCaches).Set(nameof(input.Code), input.Code);
            var bytes = ImageExtention.GetValidCodeBytes(input);
            return FileExtension.FileContentResult(bytes, "image/png");
        }
        /// <summary>
        /// Get获取验证码图片Basement4
        /// </summary>
        /// <returns></returns>
        public string GetValidCodeString()
        {
            var input = new ValidCodeImageInputDto();
            _cacheManager.GetCache(NetCoreConsts.PersonalCaches).Set(nameof(input.Code), input.Code);
            return ImageExtention.GetValidCodeString(input);
        }


        #endregion
    }
}
